package com.h;


import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

/**
 *
 * @author he.antai
 *
 */
public class MyListView extends ListView {
	
	private int pageIdx=0;
	
	private View loadMoreView;
	private TextView loadMoreTv;
	
	private MyAdapter a;
	
	/**成功及异常时消息通信，由主页面传过来*/
	private Handler tipHandler;
	
	
	public MyListView(Context context,AttributeSet attributeSet) {
		super(context, attributeSet);
	}

	public MyListView(Context context,Handler tipHandler) {
		super(context);
		this.tipHandler=tipHandler;
		loadMoreView = inflate(context,R.layout.load_more, null);
		loadMoreView.setVisibility(View.INVISIBLE);
		loadMoreView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				nextPage();
			}
		});
		
		loadMoreTv=(TextView) loadMoreView.findViewById(R.id.loadMoreButton);
		addFooterView(loadMoreView);
		
		a=new MyAdapter(context);
		setAdapter(a);
		
		nextPage();
	}
	
	private void add(List<Object> list){
		a.add(list);
		a.notifyDataSetChanged();
	}
	
	private void nextPage(){
		loadMoreView.setVisibility(View.VISIBLE);
		loadMoreTv.setText("加载中...");
		
		new GetDataThread(handler,pageIdx).start();
	}
	
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			System.out.println("msg.what:"+msg.what);
			
			Message m=new Message();//同一个Message不能被send两次
			if(msg.what==1){
				m.what=1;
			}
			tipHandler.sendMessage(m);
			
			System.out.println("pageIdx:"+pageIdx);
			if(pageIdx==2){
				loadMoreTv.setText("无更多数数据");
				loadMoreView.setEnabled(false);
				return;
			}
			
			List<Object> list=(List<Object>) msg.getData().getSerializable("data");
			
			add(list);
			loadMoreTv.setText("点击加载更多");
			pageIdx++;
		}
	};
	

}
